import InterceptorManager from './core/InterceptorManager'
import localStorage from '@/localStorage'
import http from './'

let interceptors = {
	request: new InterceptorManager(),
	response: new InterceptorManager()
}

// 请求拦截
interceptors.request.use(function(config) {
	config.header.Authorization = `Bearer ${localStorage.getToken()}`
	return config
}, undefined)

// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []

// 响应拦截
interceptors.response.use(async function(res) {
	if (res.data.statusCode === 6) {
		let {
			config
		} = res
		if (!isRefreshing) {
			isRefreshing = true
			let userinfo = localStorage.getUserinfo()
			if (!userinfo || !userinfo.openId) return
			let [, {
				data
			}] = await uni.request({
				url: `${config.baseURL}/token/open/${userinfo.openId}`,
				method: 'GET'
			})
			localStorage.setToken(data.data.token)
			requests.forEach(cb => cb())
			// 重试完了清空这个队列
			requests = []
			isRefreshing = false
			return http.request(config)
		} else {
			return new Promise((resolve) => {
				requests.push(() => {
					resolve(http.request(config))
				})
			})
		}
	} else if (res.data.statusCode !== 0) {
		uni.showToast({ 
			icon: 'none',
			position: 'bottom',
			title: res.data.message
		})
		throw new Error(res.data.message)
	}
	return res
}, err => {
	uni.showToast({
		icon: 'none',
		position: 'bottom',
		title: '网络异常'
	})
})

export default interceptors
